/**
 * @param {string} s
 * @return {number}
 */
var longestValidParentheses = function(s,areas) {
    var map = {
        '(' : -1,
        ')': 1
    };
    let merge = (areas) => {
        // 合并相邻的区间
        let newAreas = [];
        let newAreasLen = -1;
        let lastIndex = -1;
        for (let i = 0;i < areas.length;i++) {
            if (areas[i][1] <= lastIndex) continue;
            if (newAreas.length) {
                if (areas[i][0] === newAreas[newAreasLen][1] + 1) {
                    newAreas[newAreasLen][1] = areas[i][1];
                    lastIndex = areas[i][1];
                } else {
                    newAreas.push(areas[i]);
                    lastIndex = areas[i][1];
                    newAreasLen++;
                }
            } else {
                newAreas.push(areas[i]);
                lastIndex = areas[i][1];
                newAreasLen = 0;
            }
        }
        return newAreas;
    };
    areas = areas || [];
    if (!areas.length) {
        for (let i = 1;i < s.length;i++) {
        if (s[i - 1] === '(' && s[i] === ')') {
            areas.push([i-1,i]);
            i++;
        }
    }
    }
    show(s,areas);

    let strLen = s.length;
    let tryMerge = areas => {
        let max = 0;
        areas = merge(areas);
        areas.forEach((arr,ind) => {
            let from = ind ? areas[ind - 1][1] : 0;
            let to = areas[ind + 1] || [0,strLen];
            to = to[1];
            while (arr[0] > from && arr[1] < to) {
                if (s[arr[0] - 1] === '(' && s[arr[1] + 1] === ')') {
                    arr[0]--;
                    arr[1]++;
                } else {
                    break;
                }
            }
        });
        areas = merge(areas);
        // show(s,areas);
        areas.forEach(arr => {
            let t = arr[1] - arr[0] + 1;
            max = max > t ? max : t;
        });
        return {
            max,areas
        };
    }

    // areas = merge(areas);

    if (areas.length) {
        let t1 = tryMerge(areas);
        let max = t1.max;
        areas = t1.areas;

        while (true) {
            t1 = tryMerge(areas);
            if (t1.max === max && JSON.stringify(t1.areas) === JSON.stringify(areas)) {
                break;
            }
            areas = t1.areas;
            max = t1.max;
        }
        return max;
    } else {
        return 0;
    }
};

function show(s,area) {
    console.log(area.map(a => {
        return `[${a[0]},${a[1]}]{${a[1] - a[0] + 1}}`
    }).join('\t'));
    console.log(area);
    let str = ``;
    let last = 0;
    area.forEach(_ => {
        str += s.substring(last,_[0]) + '\t[' + s.substring(_[0],_[1] + 1) + ']\t';
        last = _[1] + 1;
    });
    console.log(str + s.substring(last));
}

if (module) {
    module.exports = {
        longestValidParentheses
    }
}
